<template>
  <a-modal
    :title="fullScreenTitle"
    :visible="visible"
    @ok="handleCancel"
    @cancel="handleCancel"
    :width="width"
    :class="{ myFullScreen: fullScreen }"
  >
    <a-form-model ref="form" :model="form" :rules="validatorRules">
      <a-row>
        <a-col :span="3">法人名称 </a-col>
        <a-col :span="3">用户名称 </a-col>
        <a-col :span="2">受控 </a-col>
        <a-col :span="2">数据分区 </a-col>
        <a-col :span="3">分类字段 </a-col>
        <a-col :span="7">权限 </a-col>
        <a-col :span="4">操作 </a-col>
      </a-row>
      <a-row>
        <a-col :span="3">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="bankNoCd">
            <a-select
              show-search
              allow-clear
              v-model="form.bankNoCd"
              style="width: 100%"
              placeholder="请选择法人"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
              @change="selectBankNoCd"
            >
              <a-select-option v-for="item in reportsOptions" :key="item.value" :value="item.value" :label="item.label">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="3">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="userName">
            <a-select
              show-search
              allow-clear
              v-model="form.userName"
              style="width: 100%"
              placeholder="请选择用户"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
            >
              <a-select-option
                v-for="item in roleList[form.bankNoCd]"
                :key="item.value"
                :value="item.value"
                :label="item.label"
                :disabled="list.some((el) => el.bankNoCd === form.bankNoCd && el.userName === item.value)"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="2">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="flag">
            <!-- <j-tree-select
              ref="treeSelect"
              placeholder="请选择受控"
              v-model="form.flag"
              dict="llbb_param_config,name,code"
              pidValue="1508964694614441986"
              hasChildField="has_child"
            /> -->
            <a-select
              show-search
              allow-clear
              v-model="form.flag"
              style="width: 100%"
              placeholder="请选择受控"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
            >
              <a-select-option v-for="item in flagList" :key="item.value" :value="item.value" :label="item.label">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="2">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="splitType">
            <a-select
              show-search
              allow-clear
              v-model="form.splitType"
              style="width: 100%"
              placeholder="请选择数据分区"
              @change="select"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
            >
              <a-select-option
                v-for="item in splitTabFieldList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="3">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="splitTabField">
            <a-select
              show-search
              allow-clear
              v-model="form.splitTabField"
              style="width: 100%"
              placeholder="请选择分类字段"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
              :disabled="form.splitType !== '2'"
              @change="handleSelect"
            >
              <a-select-option v-for="item in typeList" :key="item.value" :value="item.value" :label="item.label">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="7">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="splitTabRules">
            <a-tree-select
              show-search
              style="width: 100%"
              v-model="form.splitTabRules"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              multiple
              :maxTagCount="1"
              tree-default-expand-all
              :treeData="
                form.splitType === '1'
                  ? nbjghLists[form.bankNoCd]
                  : form.splitType === '2'
                  ? splitTabRules[form.splitTabField]
                  : []
              "
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
              :disabled="form.splitType === '0'"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item>
            <a-button
              v-show="!(form.hasOwnProperty('id') || form.hasOwnProperty('vId'))"
              icon="plus"
              @click="addDomain"
              type="primary"
              :loading="confirmLoading"
            >
              添加
            </a-button>
            <a-button @click="removeDomain()" v-show="form.hasOwnProperty('id') || form.hasOwnProperty('vId')">
              取消
            </a-button>
            <a-button
              v-show="form.hasOwnProperty('id') || form.hasOwnProperty('vId')"
              :style="{ marginLeft: '8%' }"
              icon="check"
              @click="editDomain"
              type="primary"
              :loading="confirmLoading"
            >
              保存
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-table
      :columns="columns"
      :data-source="list"
      :rowKey="(record) => record.id"
      :pagination="false"
      :loading="confirmLoading"
    >
      <span
        slot="bankNoCd"
        slot-scope="text"
        :title="(text && reportsOptions.length > 0 && filterLabel(text, reportsOptions)) || ''"
      >
        {{ (text && reportsOptions.length > 0 && filterLabel(text, reportsOptions)) || '' }}
      </span>
      <span
        slot="userName"
        slot-scope="text, record"
        :title="
          (text &&
            roleList &&
            roleList[record.bankNoCd] &&
            roleList[record.bankNoCd].length > 0 &&
            filterLabel(text, roleList[record.bankNoCd])) ||
          ''
        "
      >
        {{
          (text &&
            roleList &&
            roleList[record.bankNoCd] &&
            roleList[record.bankNoCd].length > 0 &&
            filterLabel(text, roleList[record.bankNoCd])) ||
          ''
        }}
      </span>
      <span slot="flag" slot-scope="text">
        {{ (flagList.length > 0 && filterLabel(text, flagList)) || '' }}
      </span>
      <span slot="splitType" slot-scope="text">
        {{ (text && splitTabFieldList.length > 0 && filterLabel(text, splitTabFieldList)) || '' }}
      </span>
      <span slot="splitTabField" slot-scope="text, record">
        {{ record.splitType === '2' ? text && typeList.length > 0 && filterLabel(text, typeList) : '' }}
      </span>
      <span
        slot="splitTabRules"
        slot-scope="text, record"
        :title="
          record.splitType != '0'
            ? text &&
              ((nbjghList && nbjghList[record.bankNoCd] && nbjghList[record.bankNoCd].length > 0) ||
                (splitTabRules &&
                  splitTabRules[record.splitTabField] &&
                  splitTabRules[record.splitTabField].length > 0)) &&
              filterRuler(
                text,
                record.splitType === '1' ? nbjghList[record.bankNoCd] : splitTabRules[record.splitTabField]
              )
            : ''
        "
      >
        {{
          record.splitType != '0'
            ? text &&
              ((nbjghList && nbjghList[record.bankNoCd] && nbjghList[record.bankNoCd].length > 0) ||
                (splitTabRules &&
                  splitTabRules[record.splitTabField] &&
                  splitTabRules[record.splitTabField].length > 0)) &&
              filterRuler(
                text,
                record.splitType === '1' ? nbjghList[record.bankNoCd] : splitTabRules[record.splitTabField]
              )
            : ''
        }}
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)" v-has="'reportManage:edit'">编辑</a>
        <a-popconfirm title="确定删除吗?" @confirm="() => removeDomain(record)">
          <a :style="{ marginLeft: '15px' }" v-has="'juridicalPerson:edit'"> 删除 </a>
        </a-popconfirm>
      </span>
    </a-table>
  </a-modal>
</template>

<script>
import FullScreenTitle from '@/components/LIbb/FullScreenTitle'
import Mechanism from '@/components/Mechanism'

import {
  queryBankNoCdList,
  queryRoleList,
  queryThemeList,
  queryRuleList,
  queryNbjghList,
  queryFieldsByReportCode,
  getDictItem,
  getRoleReport,
  getSplitTabRules,
  busTypeAuthAdd,
  getSplitTabField,
  editLlbbRoleReport,
  delLlbbRoleReport,
  addLlbbRoleReport,
  loadTreeData,
} from '@/api/api'

const columns = [
  {
    title: '法人名称',
    dataIndex: 'bankNoCd',
    scopedSlots: { customRender: 'bankNoCd' },
    ellipsis: true,
  },
  {
    title: '用户名称',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
  },
  {
    title: '受控',
    dataIndex: 'flag',
    scopedSlots: { customRender: 'flag' },
    ellipsis: true,
  },
  {
    title: '数据分区',
    dataIndex: 'splitType',
    scopedSlots: { customRender: 'splitType' },
    ellipsis: true,
  },
  {
    title: '分类字段',
    dataIndex: 'splitTabField',
    scopedSlots: { customRender: 'splitTabField' },
    ellipsis: true,
  },
  {
    title: '权限',
    dataIndex: 'splitTabRules',
    scopedSlots: { customRender: 'splitTabRules' },
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'LlbbJuridicalPersonRuleForm',
  components: { FullScreenTitle,Mechanism },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    visible: {
      type: Boolean,
      default: false,
      required: false,
    },
    detail: {
      type: Object,
      default: false,
      required: false,
    },
  },
  data() {
    let validatePass = (rule, value, callback) => {
      if (this.form.splitType != '0') {
        if (value.length <= 0) {
          callback(new Error('请选择权限'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      confirmLoading: false,
      width: '1200px',
      columns,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 0 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
      validatorRules: {
        bankNoCd: [{ required: true, message: '请选择法人!' }],
        userName: [{ required: true, message: '请选择用户!' }],
        flag: [{ required: true, message: '请选择是否受控!' }],
        splitType: [{ required: true, message: '请选择数据分区!' }],
        splitTabField: [{ required: false, message: '请选择分类!' }],
        splitTabRules: [{ validator: validatePass, message: '请选择权限!' }],
      },
      reportsOptions: [],
      vId: 2,
      form: {
        bankNoCd: '',
        userName: '',
        flag: '',
        splitType: '',
        splitTabField: '',
        splitTabRules: [],
      },
      roleList: {},
      roleReport: [],
      flagList: [],
      splitTabFieldList: [],
      typeList: [],
      nbjghList: {},
      nbjghLists: {},
      splitTabRules: {},
      list: [],
      width: 1200,
      fullScreen: false,
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.initReportList2()
    // this.initRoleList()
    // this.initNbjghList()
    this.initLoadTreeData()
    this.initLoadFlag()
  },
  watch: {
    detail(newValue, oldValue) {
      if (newValue.reportTabName) {
        this.initList(newValue.reportTabName)
      }
    },
  },
  methods: {
    fullScreenTitle() {
      return (
        <full-screen-title
          title="权限配置"
          fullCoderEdit={this.fullCoderEdit}
          fullScreen={this.fullScreen}
        ></full-screen-title>
      )
    },
    fullCoderEdit() {
      this.width = this.fullScreen ? 1200 : '100%'
      this.fullScreen = !this.fullScreen
    },
    //初始化是否受控
    initLoadFlag() {
      loadTreeData({
        pid: '1508964694614441986',
        tableName: 'llbb_param_config',
        condition: '',
        text: 'name',
        code: 'code',
        pidField: 'pid',
        hasChildField: 'has_child',
      }).then((res) => {
        if (res.message) {
          this.flagList = res.result.map((item, index, arr) => {
            let c = { label: item.title, value: item.key, id: item.key }
            return c
          })
        }
      })
    },
    //初始化数据分区
    initLoadTreeData() {
      loadTreeData({
        pid: '1509081717956755458',
        tableName: 'llbb_param_config,name,code',
        tableName: 'llbb_param_config',
        condition: '',
        text: 'name',
        code: 'code',
        pidField: 'pid',
        hasChildField: 'has_child',
      }).then((res) => {
        if (res.message) {
          this.splitTabFieldList = res.result.map((item, index, arr) => {
            let c = { label: item.title, value: item.key, id: item.key }
            return c
          })
        }
      })
    },
    //权限列表
    initList(reportCode) {
      getRoleReport({ reportCode: reportCode || this.detail.reportTabName }).then((res) => {
        if (res.code === 200) {
          let data = res.result.records || []
          data = data.map((item) => {
            item.splitTabRules =
              item && item.splitTabRules && item.splitTabRules.length > 0 ? item.splitTabRules.split(',') : []
            if (item.splitType === '2') {
              if (!(this.splitTabRules[item.splitTabField] && this.splitTabRules[item.splitTabField].length > 0)) {
                this.initSplitTabRules(item.splitTabField)
              }
            }
            if (item.bankNoCd) {
              this.selectBankNoCd(item.bankNoCd)
            }
            return item
          })
          this.list = data
        } else {
          this.$message.warning('服务器出错')
        }
        this.confirmLoading = false
      })
    },
    //分类字段选择
    handleSelect(value) {
      let data = this.form
      data.splitTabRules = []
      this.form = JSON.parse(JSON.stringify(data))
      if (!(this.splitTabRules[value] && this.splitTabRules[value].length > 0)) {
        this.initSplitTabRules(value)
      }
    },
    //数据分区选择
    select(value) {
      let data = this.form
      data.splitTabField = ''
      data.splitTabRules = []
      this.form = data
      if (value === '2' && this.typeList.length <= 0) {
        this.initSplitTabField()
      }
      // if (value === '0') {
      //   this.$refs.form.validateField('splitTabRules')
      // }
    },

    loopTree(treeList, list) {
      treeList.map((item) => {
        item.children = list.filter((el) => el.PARENTID === item.ID) || []
        if (item.children.length > 0) {
          this.loopTree(item.children, list)
        }
      })
    },
    //初始化分类字段
    initSplitTabField() {
      getSplitTabField({ reportCode: this.detail.reportTabName }).then((res) => {
        if (res.code === 200) {
          this.typeList = res.result.map((item, index, arr) => {
            let c = { label: item.typeFieldName, value: item.typeField, id: item.typeField }
            return c
          })
        } else {
          this.$message.warning('服务器出错')
        }
      })
    },
    //初始化分类树形多选字段
    initSplitTabRules(value) {
      getSplitTabRules({ reportCode: this.detail.reportTabName, splitTabField: value }).then((res) => {
        if (res.code === 200) {
          let data = this.splitTabRules
          let list = res.result || []
          data[value] = list.map((item, index, arr) => {
            return { label: item.NAME, value: item.CODE, id: item.CODE }
          })
          this.splitTabRules = data
        } else {
          this.$message.warning('服务器出错')
        }
      })
    },
    loop(list) {
      return list.map((item, index, arr) => {
        let c = { label: item.NAME || item.DEPARTNAME, value: item.CODE || item.ORGCODE, id: item.CODE || item.ORGCODE }
        if (item.children) {
          c.children = this.loop(item.children)
        }
        return c
      })
    },
    filterLabel(value, list) {
      if (list.length && value) {
        let data = list.filter((item) => item.value === value)[0]
        return data ? data.label : ''
      }
      return ''
    },
    filterRuler(ids = [], list = []) {
      let names = []
      if (ids) {
        ids.map((item) => {
          if (list && list.some((el) => el.value === item)) {
            let name = list.filter((el) => el.value === item)[0]
            if (name) {
              names.push(name.label)
            }
          }
        })
      }
      return names.length > 0 ? names.join(',') : ''
    },
    handleEdit(record) {
      this.form = JSON.parse(JSON.stringify(record))
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
    editDomain() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          const splitTabRules = this.form.splitTabRules.length > 0 ? this.form.splitTabRules.join(',') : ''
          editLlbbRoleReport({ ...this.form, splitTabRules }).then((res) => {
            if (res.code === 200) {
              this.$message.success('修改成功')
              this.initList()
              this.form = {}
            } else {
              this.$message.warning('服务器出错')
            }
          })
        } else {
          return false
        }
      })
    },
    addDomain() {
      this.$refs.form.validate((valid) => {
        console.log('%c [ valid ]-398', 'font-size:13px; background:pink; color:#bf2c9f;', this.form)
        if (valid) {
          if (this.list.some((el) => el.bankNoCd === this.form.bankNoCd && el.userName === this.form.userName)) {
            this.$message.error('用户重复！')
            return false
          }
          const splitTabRules = this.form.splitTabRules.length > 0 ? this.form.splitTabRules.join(',') : ''
          this.confirmLoading = true
          addLlbbRoleReport({ ...this.form, splitTabRules, reportCode: this.detail.reportTabName }).then((res) => {
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.initList()
            } else {
              this.$message.warning('服务器出错')
            }
          })
          this.form = {}
          this.resetForm()
        } else {
          return false
        }
      })
    },
    // 删除
    removeDomain(record) {
      if (record && record.id && !this.confirmLoading) {
        this.confirmLoading = true
        delLlbbRoleReport({ id: record.id }).then((res) => {
          if (res.code === 200) {
            this.initList()
            this.form = {}
            this.resetForm()
          } else {
            this.$message.warning('服务器出错')
          }
        })
      } else {
        this.form = {}
        this.resetForm()
      }
    },
    //初始化报表表记录
    initReportList2() {
      queryBankNoCdList().then((res) => {
        if (res.code === 200) {
          this.reportsOptions = res.result.map((item, index, arr) => {
            let c = { label: item.bankname, value: item.bankNoCd, id: item.bankNoCd }
            return c
          })
        } else {
          this.$message.warning('服务器出错')
        }
      })
    },
    // 查询机构
    selectUser(value) {
      if (!(this.nbjghLists && this.nbjghLists[value])) {
        queryNbjghList({ nbjgh: 'nbjgh', bankNoCd: value }).then((res) => {
          if (res.code === 200) {
            let data1 = this.nbjghLists
            let data2 = this.nbjghList
            let list = res.result || []
            let treeList =
              list.filter((item) => item.PARENTID === '' || item.PARENTID === null || item.PARENTID === undefined) || []
            if (list.length > 0) {
              this.loopTree(treeList, list)
            }
            data1[value] = this.loop(treeList)
            data2[value] = this.loop(list)
            this.nbjghLists = JSON.parse(JSON.stringify(data1))
            this.nbjghList = JSON.parse(JSON.stringify(data2))
          } else {
            this.$message.warning('服务器出错')
          }
        })
      }
    },
    //初始化机构
    initNbjghList(value) {
      queryNbjghList({ nbjgh: 'nbjgh', bankNoCd: value }).then((res) => {
        if (res.code === 200) {
          if (res.result && res.result.length > 0) {
            let list = res.result || []
            let treeList =
              list.filter((item) => item.PARENTID === '' || item.PARENTID === null || item.PARENTID === undefined) || []
            if (list.length > 0) {
              this.loopTree(treeList, list)
            }
            this.nbjghLists = this.loop(treeList)
            this.nbjghList = this.loop(list)
          }
        } else {
          this.$message.warning('服务器出错')
        }
      })
    },
    //查询用户
    selectBankNoCd(value) {
      if (!(this.roleList && this.roleList[value])) {
        queryRoleList({ bankNoCd: value }).then((res) => {
          if (res.code === 200) {
            let data = this.roleList
            data[value] = res.result.map((item, index, arr) => {
              let c = { label: item.REALNAME, value: item.USERNAME, id: item.USERNAME }
              return c
            })
            this.roleList = JSON.parse(JSON.stringify(data))
          } else {
            this.$message.warning('服务器出错')
          }
        })
      }
      if (!(this.nbjghLists && this.nbjghLists[value])) {
        this.selectUser(value)
      }
    },
    // //初始化用户
    // initRoleList(value) {
    //   queryRoleList({ bankNoCd: value }).then((res) => {
    //     if (res.code === 200) {
    //       let data = this.roleList
    //       data[value] = res.result.map((item, index, arr) => {
    //         let c = { label: item.ROLENAME, value: item.ID, id: item.ID }
    //         return c
    //       })
    //       this.roleList = data
    //     } else {
    //       this.$message.warning('服务器出错')
    //     }
    //   })
    // },
    //获取权限配置列表
    initRoleReport(item) {
      getRoleReport(item).then((res) => {
        if (res.code === 200) {
          this.roleReport = res.result.map((item, index, arr) => {
            let c = { label: item.ROLENAME, value: item.ID, id: item.ID }
            return c
          })
        } else {
          this.$message.warning('服务器出错')
        }
      })
    },
    // 关闭
    handleCancel() {
      this.fullScreen = false
      this.width = 1200
      this.$emit('cancel')
    },
  },
}
</script>
<style lang="less" scoped>
.myFullScreen /deep/ .ant-modal {
  top: 0;
  padding-bottom: 0;
}
.myFullScreen /deep/ .ant-modal-content {
  height: 100vh;
}
</style>